﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DNA.Mvc.Data.Xml;
using DNA.Utility;
using System.IO;
using System.Drawing;


namespace DNA.Mvc.Exporting.Exporters
{
    public class PackageExporter : Exporter
    {
        public override string Name
        {
            get { return "package"; }
            set { }
        }

        public override bool Visible
        {
            get
            {
                return false;
            }
        }

        public override void Execute(ExportingContext context)
        {
            var package = GetMatch<Package>(context);
            var pkgPath = context.Destination + (context.Destination.EndsWith("\\") ? "" : "\\");
            var filename = pkgPath + "manifest.xml";

            if (package.Images.Count > 0)
            {
                var imgPath = pkgPath + "\\images";
                if (!Directory.Exists(imgPath))
                    Directory.CreateDirectory(imgPath);

                foreach (var img in package.Images)
                {
                    if (!string.IsNullOrEmpty(img.Url) && (File.Exists(img.Url)))
                    {
                        var imgFileName = Path.GetFileName(img.Url);
                        var srcImageFilename = img.Url;
                        var destImageFilename = imgPath + "\\" + imgFileName;
                        File.Copy(srcImageFilename, destImageFilename);
                        img.Url = "images/" + imgFileName;

                        try
                        {
                            using (var imgInstance = Image.FromFile(srcImageFilename))
                            {
                                img.Width = imgInstance.Width;
                                img.Height = imgInstance.Height;
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
            }
            var descriptor = PackageConverter.Convert(package);
            XmlSerializerUtility.SerializeToXmlFile<PackageDescriptor>(filename, descriptor);
        }
    }
}
